<template>
    <div ref="chart4" style="height: 140px;">

    </div>
</template>

<script setup lang="ts">
import axios from "axios";
import * as echarts from "echarts";
import type { EChartsOption } from 'echarts/types/dist/echarts.d.ts'
import { onMounted, ref } from "vue";

let option: EChartsOption = {
    xAxis: {
        type: 'category',
        boundaryGap: true,
        data: [],
        max: 9
    },
    yAxis: {
        type: 'value',
        boundaryGap: [0.2, 0.2]
    },
    series: [],
    grid: {
        height: 170,
        top: 10
    }
}

let chart4 = ref<HTMLDivElement | null>(null)
let myECharts: echarts.ECharts | null = null

function init() {
    myECharts = echarts.init(chart4.value)
    axios.get("/api/rank.json").then(({ data }) => {
        // console.log(data);
        data = data.sort((a: any, b: any) => b.value - a.value)
        const dataName = data.map((item: any) => item.name)
        const dataValue = data.map((item: any) => item.value);
        let count = 10

        const updateChart = () => {
            (option.xAxis as any).data = count <= dataName.length ?
                dataName.slice(count - 10, count) :
                [...dataName.slice(count - 10, dataName.length), ...dataName.slice(0, count - dataName.length)];
            option.series = [];
            (option.series as any).push({
                type: "bar",
                data: count <= dataValue.length ?
                    dataValue.slice(count - 10, count) :
                    [...dataValue.slice(count - 10, dataValue.length), ...dataValue.slice(0, count - dataValue.length)],
                itemStyle: {
                    color: {
                        type: 'linear', // 明确渐变类型
                        x: 0, y: 0, x2: 0, y2: 1, // 垂直渐变（上到下）
                        colorStops: [
                            { offset: 0, color: '#5252ED' },
                            { offset: 1, color: '#AB6EE5' }
                        ]
                    },
                    borderRadius: [20, 20, 0, 0]
                }
            })
            count < data.length + 9 ? count++ : count = 10
            myECharts?.setOption(option)
        }
        updateChart()
        setInterval(() => {
            updateChart()
        }, 2000)
    })
}


onMounted(() => {
    init()
    window.addEventListener('resize', () => { myECharts?.resize() });
})
</script>

<style scoped></style>